﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public partial class UILogin : UIBase
{
    public InputField inputAccount;
    public InputField inputPassword;
    public InputField inputIp;
    public InputField inputPort;
    public Toggle togglePassword;

    public override void OnButtonCloseClick()
    {
        base.OnButtonCloseClick();
        SceneMgr.Instance.LoadScene(SceneName.SceneMain);
    }

    public void OnTogglePasswordChange(Toggle toggle)
    {
        SetInputPasswordType(toggle);
    }

    private void SetInputPasswordType(Toggle toggle)
    {
        if (toggle.isOn)
            inputPassword.contentType = InputField.ContentType.Password;
        else
            inputPassword.contentType = InputField.ContentType.Standard;
        inputPassword.ForceLabelUpdate();
    }
    protected override void onVisible()
    {
        this.inputIp.text = PlayerPrefs.GetString(this.GetUIName() + "ip", "127.0.0.1"); //"43.136.51.58");
        this.inputPort.text = PlayerPrefs.GetString(this.GetUIName() + "port", "8282"); //"8889");

        var account = PlayerPrefs.GetString(this.GetUIName() + "account");
        if (!string.IsNullOrEmpty(account))
            this.inputAccount.text = account;

        var psw = PlayerPrefs.GetString(this.GetUIName() + "psw");
        if (!string.IsNullOrEmpty(psw))
            this.inputPassword.text = psw;

        togglePassword.isOn = PlayerPrefs.GetInt(this.GetUIName() + "pswMode", 0) == 1;
        SetInputPasswordType(togglePassword);

        Facade.Instance.RegistNetEvent(nameof(login_rsp), OnHandleLoginRsp);
    }

    protected override void OnInvisible()
    {
        PlayerPrefs.SetString(this.GetUIName() + "ip", this.inputIp.text);
        PlayerPrefs.SetString(this.GetUIName() + "port", this.inputPort.text);

        var account = this.inputAccount.text.Trim();
        if (!string.IsNullOrEmpty(account))
            PlayerPrefs.SetString(this.GetUIName() + "account", account);

        var psw = this.inputPassword.text.Trim();
        if (!string.IsNullOrEmpty(psw))
            PlayerPrefs.SetString(this.GetUIName() + "psw", psw);

        PlayerPrefs.SetInt(this.GetUIName() + "pswMode", togglePassword.isOn ? 1 : 0);

        Facade.Instance.UnRegistNetEvent(nameof(login_rsp), OnHandleLoginRsp);
    }

    private bool IsFillAccountOrPsw()
    {
        string account = this.inputAccount.text.Trim();
        string psw = this.inputPassword.text.Trim();
        if (string.IsNullOrEmpty(account))
        {
            Debug.LogError("account = null");
            UITips.Instance.Show(XLocalization.Get("请输入账号"));
            return false;
        }
        if (string.IsNullOrEmpty(psw))
        {
            Debug.LogError("psw = null");
            UITips.Instance.Show(XLocalization.Get("请输入密码"));
            return false;
        }
        return true;
    }
}
